<template>
  <div v-if="proxy.isAuth(['ROOT', 'CHECKUP REPORT:SELECT'])">
    <el-form :inline="true" :model="dataForm" :rules="dataRule" ref="form">
      <el-form-item prop="name">
        <el-input
            v-model="dataForm.name"
            maxlength="20"
            class="input"
            clearable
            placeholder="姓名"
        />
      </el-form-item>

      <el-form-item prop="tel">
        <el-input
            v-model="dataForm.tel"
            placeholder="电话号码"
            maxlength="11"
            class="input"
            clearable
        />
      </el-form-item>
      <el-form-item prop="waybillCode">
        <el-input
            v-model="dataForm.waybillCode"
            placeholder="快递单号"
            maxlength="24"
            class="input"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchHandle()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <!--        <el-upload
                    :action="upload.action"
                    name="file"
                    accept=".xlsx"
                    :headers="upload.headers"
                    :show-file-list="false"
                    :before-upload="excelBeforeUpload"
                    :on-success="excelUploadSuccess"
                    :on-error="excelUploadError"
                >
                  <el-button type="primary">导入运单</el-button>
                </el-upload>-->
      </el-form-item>

      <el-form-item class="mold">
        <el-radio-group v-model="dataForm.statusLabel" @change="searchHandle()">
          <el-radio-button label="全部">全部</el-radio-button>
          <el-radio-button label="未生成">未生成</el-radio-button>
          <el-radio-button label="已生成">已生成</el-radio-button>
          <el-radio-button label="已寄出">已寄出</el-radio-button>
        </el-radio-group>
      </el-form-item>

    </el-form>
    <el-table :data="data.dataList" :header-cell-style="{'background': '#f5f7fa'}" border :loading="data.loading">

      <el-table-column type="index" header-align="center" align="center" width="120" label="序号" fixed>
        <template #default="scope">
          <span>{{ (data.pageIndex - 1) * data.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column header-align="center" align="center" label="姓名" min-width="150" fixed>
        <template #default="scope">
          <span class="customer-name"
                @dblclick="copyAddressHandle(scope.row.name,scope.row.mailingAddress)">{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="sex" header-align="center" align="center" label="性别" width="130"/>


      <el-table-column prop="age" header-align="center" align="center" label="年龄" width="130"/>


      <el-table-column prop="hideTel" header-align="center" align="center" label="电话" width="180"/>

      <el-table-column prop="status" header-align="center" align="center" label="报告状态" width="140"/>

      <el-table-column prop="waybillCode" header-align="center" align="center" label="快递单号" width="280"/>

      <el-table-column prop="waybillDate" header-align="center" align="center" label="寄出日期" width="170"/>

      <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
        <template #default="scope">
          <el-button
              type="text"
              :disabled="scope.row.disabled"
              @click="createReportHandle(scope.row.id)"
          >
            生成报告
          </el-button>
          <el-button
              type="text"
              :disabled="scope.row.status !== '已生成'"
              @click="downloadReportHandle(scope.row.name, scope.row.filePath)"
          >
            下载报告
          </el-button>
          <el-button
              type="text"
              :disabled="scope.row.status !== 'NOW1'"
              @click="identifyWaybillHandle(scope.row.id, scope.row.name, scope.row.tel)"
          >
            录入运单
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="data.pageIndex"
        :page-size="data.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="data.totalCount"
        layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </div>
  <el-dialog
      title="录入运单"
      v-if="proxy.isAuth(['ROOT', 'CHECKUP_REPORT:UPDATE'])"
      :close-on-click-modal="false"
      v-model="dialog.visible"
      width="420px"
  >
    <!-- 提示信息 -->
    <el-alert
        title="请上传快递运单照片，系统将自动识别运单中的信息，然后请您核对无误后，提交运单!"
        type="success"
        :closable="false"
    />

    <!-- 上传运单 -->
    <el-upload
        :action="dialog.upload.action"
        name="file"
        accept=".jpg,.jpeg"
        :headers="dialog.upload.headers"
        :data="dialog.upload.data"
        :show-file-list="false"
        :before-upload="waybillBeforeUpload"
        :on-success="waybillUploadSuccess"
        :on-error="waybillUploadError"
    >
      <el-button type="primary">上传运单</el-button>
    </el-upload>

    <!-- 运单信息核对 -->
    <el-divider border-style="dashed">认真核对下方运单信息</el-divider>
    <table>
      <tr>
        <th>收件人姓名:</th>
        <td>{{ dialog.data.recName }}</td>
        <th>收件人电话:</th>
        <td>{{ dialog.data.recTel }}</td>
      </tr>
      <tr>
        <th>运单号码:</th>
        <td>{{ dialog.data.waybillCode }}</td>
      </tr>
    </table>
    <template #footer>
     <span class="dialog-footer">
    <el-button @click="dialog.visible = false">取消</el-button>
    <el-button
        type="primary"
        :disabled="dialog.data.waybillCode === null || dialog.data.waybillCode === ''"
        @click="dataFormSubmit"
    >
      提交运单
    </el-button>
  </span>
    </template>

  </el-dialog>

</template>

<script setup lang="ts">
import {getCurrentInstance, reactive} from "vue";
import {dayjs, ElNotification, UploadFile} from "element-plus";
import {isBlank} from "../../utils/validate.ts"; // 导入 isSameOrBefore 插件


const {proxy} = getCurrentInstance(); // 获取当前实例的 proxy 对象
const dialog = reactive({
  visible: true,
  upload: {
    action: `${proxy.$baseUrl}/mis/checkup/report/identifyWaybill`,
    headers: {
      "token": localStorage.getItem("token") // 从 localStorage 中获取 token
    },
    data: {
      id: null
    }
  },
  data: {
    id: null,
    recName: null,
    waybillCode: null,
    name: null,
    telEnd: null
  }
});

const dataForm = reactive({
  name: null,
  tel: null,
  waybillCode: null,
  statusLabel: '全部', // 这是默认的状态标签
  status: null, // 状态，初始为 null
});

function identifyWaybillHandle(id, name, tel) {
  dialog.data.id = id;
  dialog.data.recName = null;  // Reset recipient name
  dialog.data.tel = null;  // Reset phone number
  dialog.data.waybillCode = null;  // Reset waybill code
  dialog.data.name = name;  // Set name
  dialog.data.telEnd = tel.substr(7, 4);  // Get last 4 digits of phone number
  dialog.visible = true;  // Show the dialog
}

const data = reactive({
  dataList: [],   // 数据列表，初始为空
  pageIndex: 1,   // 当前页码，默认为1
  pageSize: 10,   // 每页显示条数，默认为10
  totalCount: 0,  // 总记录数，初始为0
  loading: false  // 加载状态，默认为false
});

const dataRule = reactive({
  name: [
    {
      required: false,
      pattern: '^[\u4e00-\u9fa5]{1,10}$',  // 姓名格式正则：1-10个汉字
      message: '姓名格式错误'
    }
  ],
  tel: [
    {
      required: false,
      pattern: '^1[1-9]\\d{9}$',  // 电话格式正则：以1开头，接着是11-19之间的数字，后接9位数字
      message: '电话格式错误'
    }
  ],
  waybillCode: [
    {
      required: false,
      pattern: '^[0-9a-zA-Z]{10,24}$',  // 快递单号格式正则：10到24个字母或数字
      message: '快递单号格式错误'
    }
  ]
});

function createReportHandle(id) {
  ElNotification({
    title: '提示信息',
    message: '体检报告正在生成中，请稍后',
    duration: 1000
  });

  let json = {id: id};

  proxy.$http("/mis/checkup/report/createReport", "POST", json, true, function (resp) {
    if (resp.result) {
      proxy.$message({
        message: "体检报告创建成功",
        type: 'success',
        duration: 1200,
        onClose: () => {
          loadDatalist();
        }
      });
    } else {
      proxy.$message({
        message: "体检报告创建失败",
        type: 'error',
        duration: 1200
      });
    }
  });
}

function downloadReportHandle(name, filePath) {
  let url = `${proxy.$baseUrl}/mis/checkup/report/downloadReport?token=${localStorage.getItem('token')}&name=${name}&filePath=${encodeURIComponent(filePath)}`;

  let a = document.createElement('a');
  a.href = url;
  a.download = name;
  a.click();
}

function loadDatalist() {
  data.loading = true; // 设置 loading 状态为 true

  // 根据选中的状态标签设置状态
  if (dataForm.statusLabel === '全部') {
    dataForm.status = null;  // 如果选中的状态是 '全部'，则设置状态为 null
  } else if (dataForm.statusLabel === '未生成') {
    dataForm.status = 1;  // 如果选中的状态是 '未生成'，则设置状态为 1
  } else if (dataForm.statusLabel === '已生成') {
    dataForm.status = 2;  // 如果选中的状态是 '已生成'，则设置状态为 2
  } else {
    dataForm.status = 3;  // 其他情况，设置状态为 3
  }

  // 构造请求的 JSON 数据
  let json = {
    name: dataForm.name,
    tel: dataForm.tel,
    waybillCode: dataForm.waybillCode,
    status: dataForm.status,
    page: data.pageIndex,
    length: data.pageSize  // 假设 `data.pageSize` 存储每页的记录数量
  };

  // 发送请求
  proxy.$http('/mis/checkup/report/searchByPage', 'post', json, true, function (resp) {
    let page = resp.page;

    // 定义一个状态映射
    let temp = {
      "未生成": "1",
      "已生成": "2",
      "已寄出": "3"
    };

    // 遍历查询结果的每一项，并根据状态映射更新状态
    for (let one of page.list) {
      one.status = temp[one.status] || ""; // 根据状态映射更新状态，默认空字符串

      // 检查生成报告按钮是否禁用
      let checkupDate = dayjs(one.date); // 假设 `one.date` 是体检日期
      let isReportDisabled = dayjs().subtract(10, 'days').isSameOrBefore(checkupDate); // 判断体检日期是否在当前日期的10天之前

      // 设置按钮禁用状态
      one.disabled = isReportDisabled;
    }

    // 更新数据列表和总记录数
    data.dataList = page.list;
    data.totalCount = page.totalCount;
    data.loading = false;  // 加载完成，设置 loading 为 false
  });
}

function sizeChangeHandle(val) {
  data.pageSize = val;
  loadDatalist();
}

function searchHandle() {
  // 验证表单
  proxy.$refs['form'].validate(valid => {
    if (valid) {
      // 验证通过后清除验证
      proxy.$refs['form'].clearValidate();

      // 重置表单字段
      if (dataForm.name === '') {
        dataForm.name = null;
      }
      if (dataForm.tel === '') {
        dataForm.tel = null;
      }
      if (dataForm.waybillCode === '') {
        dataForm.waybillCode = null;
      }

      // 重置当前页为第一页
      if (data.pageIndex !== 1) {
        data.pageIndex = 1;
      }
      // 调用加载数据的函数 (假设这里调用 loadDatalist 函数)
      loadDatalist();
    } else {
      // 如果验证失败，显示错误信息
      proxy.$message({
        message: '表单验证失败，请检查输入！',
        type: 'warning',
        duration: 1200
      });
    }
  });
}

function currentChangeHandle(val) {
  data.pageIndex = val;
  loadDatalist();
}

function copyAddressHandle(name, tel, mailingAddress) {
  proxy.$message({
    message: "已复制邮寄地址",
    type: 'success',
    duration: 800
  });

  var input = document.createElement("input"); // 创建一个input元素
  input.value = `${name}, ${tel}, ${mailingAddress}`; // 设置input内容为要复制的地址信息

  document.body.appendChild(input); // 将input元素添加到DOM中
  input.select(); // 选择input的内容
  document.execCommand("Copy"); // 执行复制命令
  document.body.removeChild(input); // 删除临时input元素
}

function waybillBeforeUpload(file) {
  // 获取文件大小，单位是MB
  let size = file.size / 1024 / 1024;  // 文件大小 (MB)

  if (size > 5) {
    // 如果文件超过5MB，显示错误信息
    proxy.$message({
      message: '图片不能超过5M大小',
      type: 'error',
      duration: 1200
    });
    return false;  // 返回false，阻止上传
  }

  // 如果文件大小合适，显示识别中提示
  proxy.$message({
    message: '识别中，请稍后',
    type: 'info',
    duration: 1000
  });
  return true;  // 允许上传
}

function waybillUploadError(e) {
  // 图片上传失败时，显示错误信息
  proxy.$message({
    message: '图片上传失败',
    type: 'error',
    duration: 1200
  });
  console.error(e);  // 打印错误信息
}

function waybillUploadSuccess(resp: any, uploadFile: UploadFile, uploadFiles: UploadFile[]) {
  if (resp.msg === 'success') {
    let result = resp.result;

    // Assigning the result to dialog data
    dialog.data.recName = result.recName;
    dialog.data.recTel = result.recTel;
    dialog.data.waybillCode = result.waybillCode;

    // Check if recipient name or phone number does not match with dialog data
    if (result.recName !== dialog.data.name || result.recTel.substr(7, 4) !== dialog.data.telEnd) {
      proxy.$message({
        message: "收件人姓名或者电话与体检人不符",
        type: 'error',
        duration: 1200
      });
    }
  } else {
    proxy.$message({
      message: "上传失败，请重试",
      type: 'error',
      duration: 1200
    });
  }
}

function base64ToBlob(base64, mime) {
  // 拆分 base64 字符串
  let arr = base64.split(',');
  let bstr = atob(arr[1]);  // base64 解码
  let n = bstr.length;
  let u8arr = new Uint8Array(n);

  // 将字符转换为字节数组
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }

  // 返回 Blob 对象
  return new Blob([u8arr], {type: mime});
}

function excelUploadSuccess(resp: any, uploadfile: UploadFile, uploadfiles: UploadFile[]) {
  // 如果响应中包含 fileBase64 字段
  if (resp.hasOwnProperty("fileBase64")) {
    proxy.$message({
      message: '存在导入失败的运单，请查看下载的Excel文件',
      type: 'warning',
      duration: 2500
    });

    // 获取 base64 字符串
    let base64 = resp.fileBase64;

    // 将 base64 字符串转换为 Blob 二进制数据，并且设置 MIME 类型
    let blob = base64ToBlob(base64, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

    // 创建一个下载链接
    let a = document.createElement("a");

    // 将二进制数据转换成 URL 地址
    let href = window.URL.createObjectURL(blob);
    a.href = href;

    // 规定下载文件名称
    a.download = "导入失败的运单.xlsx";

    // 将下载链接添加到 DOM 中并触发下载
    document.body.appendChild(a);
    a.click();

    // 下载完成后移除下载链接
    document.body.removeChild(a);

    // 释放二进制数据，节省浏览器内存
    window.URL.revokeObjectURL(href);
  } else {
    // 如果没有 fileBase64 字段，执行其他操作
    proxy.$message({
      message: "运单导入成功",
      type: "success",
      duration: 1200
    });
  }
}

function excelUploadError(e) {
  proxy.$message({
    message: "Excel文件上传失败",
    type: "error",
    duration: 1200
  });
  console.error(e);
}

function dataFormSubmit() {
  let waybillCode = dialog.data.waybillCode;
  let waybillDate = dayjs().format("YYYY-MM-DD"); // 修正日期格式

  if (!isBlank(waybillCode)) {
    let json = {
      id: dialog.data.id,
      waybillCode: waybillCode,
      waybillDate: waybillDate
    };

    proxy.$http("/mis/checkup/report/ad dWaybill", "POST", json, true, function (resp) {
      if (resp.result) {
        proxy.$message({
          message: "运单提交成功",
          type: "success",
          duration: 1200,
          onClose: () => {
            dialog.visible = false;
            loadDatalist(); // 刷新数据列表
          }
        });
      } else {
        proxy.$message({
          message: "运单提交失败",
          type: "error",
          duration: 1200
        });
      }
    });
  } else {
    proxy.$message({
      message: "运单号不能为空",
      type: "warning",
      duration: 1200
    });
  }
}


loadDatalist();


</script>

<style scoped lang="less">
@import "checkup_report";
</style>
